<template>
  <v-dialog-layout
    title="绑定角色"
    width="480px"
    v-model:visible="visible"
    @confirm="formAdd.onSubmit()"
    @cancel="cancel"
  >
    <v-form-layout
      ref="formAdd"
      v-model:form-data="formData"
      :rules="rules"
      @validateSuccess="validateSuccess"
    >
      <a-form-item label="绑定角色" name="roleList" placeholder="请选择角色">
        <a-select mode="multiple" v-model:value="formData.roleList" placeholder="请选择">
          <template v-for="item in roleList" :key="item.id">
            <a-select-option :value="item.id">{{ item.roleName }}</a-select-option>
          </template>
        </a-select>
      </a-form-item>
    </v-form-layout>
  </v-dialog-layout>
</template>

<script setup lang="ts">
import { addRules } from './config'
import { ref, reactive, onMounted, Ref } from 'vue'
import { message } from 'ant-design-vue'
import useCurrentInstance from 'lib-utils/vueInstance'

const { proxy } = useCurrentInstance()
const props = withDefaults(defineProps<{
  visible: boolean,
  userId: string | number
}>(), {
  visible: false
})
const emit = defineEmits(['update:visible', 'close'])

let formAdd = ref();
let departList = ref([]);
let roleList:Ref<any[]> = ref([]);
let currentUserRoles = ref([])
const formData: {
  roleList: any[]
} = reactive({
  roleList: []
});
const rules = addRules

onMounted(() => {
  getCurrentUserRoles()
  getRoleList()
})

const getRoleList = () => {
  proxy.$http.get(proxy.$api.role.listAll).then(res => {
    roleList.value = res
  }).catch(() => {
  })
}

const getCurrentUserRoles = () => {
  proxy.$http.get(proxy.$api.user.roleList, { userId: props.userId }).then((res: any) => {
    currentUserRoles.value = res
    for (let i = 0; i < res.length; i++) {
      formData.roleList.push(res[i].roleId)
    }
  }).catch(() => {
  })
}

const validateSuccess = () => {
  let params: any = {
    userId: props.userId,
    addRoleList: [],
    deleteRoleList: []
  }

  let initRoles = currentUserRoles.value.map((item: any) => {
    return item.roleId
  })
  for (let i = 0; i < formData.roleList.length; i++) {
    if (!initRoles.includes(formData.roleList[i])) {
      params.addRoleList.push({
        userId: props.userId,
        roleId: formData.roleList[i]
      })
    }
  }
  for (let i = 0; i < initRoles.length; i++) {
    if (!formData.roleList.includes(initRoles[i])) {
      params.deleteRoleList.push(initRoles[i])
    }
  }
  proxy.$http.post(proxy.$api.user.distribute, params).then(res => {
    message.success('分配成功')
    emit('update:visible', false)
    emit('close', false)
  }).catch(err => {
  })
}

const cancel = () => {
  emit('update:visible', false)
}
</script>

<style scoped></style>